//
//  OauthViewController.swift
//  weibo
//
//  Created by nick on 15/9/23.
//  Copyright © 2015年 cn.nick. All rights reserved.
//

import UIKit
import SVProgressHUD
class OauthViewController: UIViewController ,UIWebViewDelegate{

    lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        title = "登录微博首页"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        webView.loadRequest(NSURLRequest(URL: NetworkTools.shareInstance.OauthUrl))
//        print(NetworkTools.shareInstance.OauthUrl)
        // 请求授权：https://api.weibo.com/oauth2/authorize?client_id=1516280139&redirect_uri=http://www.baidu.com网址
        
    }
    
    /// 自动填充用户信息
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = '15626414905';" +
        "document.getElementById('passwd').value = 'hgm852406';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    @objc private func back() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        print("开始加载")
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        print("加载完成")
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print("加载失败")
        print(error)
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 授权后返回的URL：https://www.baidu.com/?code=4a08346377d7bb96095fc8d8159d6b9f
        
        // 取消授权：https://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        print(request)
        // 如果没有重定向网址百度，则加载网页
        if !request.URL!.absoluteString.hasPrefix(NetworkTools.shareInstance.redirectUrl) {
            return true
        }
        // 来到这里，说明请求网址有重定向网址，下面截取请求码
        // query 是baseURL后面的部分
        if let query = request.URL?.query where query.hasPrefix("code=") {
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            // 请求token
            
            UserAccountViewModel().loadAccessToken(code, finished: { (error) -> () in
                // 如果出错返回
                if error != nil {
                    SVProgressHUD.showInfoWithStatus("您的网络不给力")
                    return
                }
                SVProgressHUD.showInfoWithStatus("登录成功")
            })
            return false
            
        }
        // return false说明，不进行加载网页。返回true，表示加载网页
        back()
        return false
    }
    
}
